﻿// saving JSON to localStorage shim
(function () {
    if (!Storage.prototype.setObject) {
        Storage.prototype.setObject = function setObject(key, obj) {
            var jsonObj = JSON.stringify(obj);
            this.setItem(key, jsonObj);
        };

    }
    if (!Storage.prototype.getObject) {
        Storage.prototype.getObject = function getObject(key) {
            var jsonObj = this.getItem(key);
            var obj = JSON.parse(jsonObj);
            return obj;
        };
    }
})();

var highScore = (function () {
    this._recordsCount = 0;

    this.saveScore = function (playerName, score) {
        // create a record object for every player
        // with his name and score
        var record = { playerName: playerName, score: score };

        // save the record in the localstorage (highscores)
        localStorage.setObject("player" + _recordsCount, record);

        // increment the number of players currently in the storage
        // so we can have unique keys
        _recordsCount++;
    }

    this.getTop5Players = function () {
        var recordsArray = [];
        var top5 = [];
        var i = 0;

        // looping through localStorage and saving the
        // records into an array so we can sort the scores
        for (i = 0; i < localStorage.length; i++) {
            var index = localStorage.key(i);
            var record = localStorage.getObject(index);
            
            recordsArray[i] = record;
        }

        // sort the array by score descending
        //recordsArray.sort(function (a, b) {
        //    return parseInt(b.score) - parseInt(a.score);
        //});
        recordsArray.sort(function compare(a, b) {
            if (b.score < a.score)
                return -1;
            if (b.score > a.score)
                return 1;
            if (b.score == a.score) {
                if (b.playerName < a.playerName)
                    return 1;
                else
                    return -1;
            }
            return 0;
        });

        // gets top 5 players and returns them as an array
        // if there are less than 5 players - gets them all
        if (recordsArray.length > 5) {
            for (i = 0; i < 5; i++) {
                top5.push(recordsArray[i]);
            }
        }
        else {
            for (i = 0; i < recordsArray.length; i++) {
                top5.push(recordsArray[i]);
            }
        }
        
        return top5;
    }

    this.clearHighScore = function () {
        localStorage.clear();
    }

    return {
        saveScore: saveScore,
        getTop5Players: getTop5Players,
        clearHighScore: clearHighScore
    }
})();